package com.kevis.zhunblog.elasticSearch.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;

import java.sql.Timestamp;

@Configuration
public class ElasticSearchConfig {

    @WritingConverter
    static class TimestampToLong implements Converter<Timestamp, Long> {
        @Override
        public Long convert(Timestamp source) {
            return source.getTime();
        }
    }
    @ReadingConverter
    static class LongToTimestamp implements Converter<Long, Timestamp> {
        @Override
        public Timestamp convert(Long source) {
            return new Timestamp(source);
        }
    }

    @Bean
    ElasticsearchConverter elasticsearchConverter(SimpleElasticsearchMappingContext mappingContext) {
        DefaultConversionService defaultConversionService = new DefaultConversionService();
        defaultConversionService.addConverter(new TimestampToLong());
        defaultConversionService.addConverter(new LongToTimestamp());
        return new MappingElasticsearchConverter(mappingContext, defaultConversionService);
    }
}
